package com.hnblc.blcwms.rest.logistics.service;

import com.hnblc.blcwms.common.constant.StringPool;
import com.hnblc.blcwms.common.interaction.Response;
import com.hnblc.blcwms.common.utils.CollectionsUtils;
import com.hnblc.blcwms.common.utils.WmsTimeUtils;
import com.hnblc.blcwms.persistent.business.odata.vo.ExpressInfoHead;
import com.hnblc.blcwms.persistent.interfaces.logistics.entity.LogisticBranchInfo;
import com.hnblc.blcwms.persistent.interfaces.logistics.entity.SenderAddress;
import com.hnblc.blcwms.persistent.interfaces.logistics.service.ILogisticBranchInfoService;
import com.hnblc.blcwms.persistent.interfaces.logistics.service.ISenderAddressService;
import com.hnblc.blcwms.rest.config.properties.PinduoduoProperties;
import com.hnblc.blcwms.rest.logistics.enums.WaybillResultEnum;
import com.hnblc.blcwms.serviceapi.api.dto.logistics.WaybillInfo;
import com.pdd.pop.sdk.http.PopAccessTokenClient;
import com.pdd.pop.sdk.http.PopBaseHttpResponse.ErrorResponse;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.api.request.*;
import com.pdd.pop.sdk.http.api.request.PddWaybillGetRequest.*;
import com.pdd.pop.sdk.http.api.response.*;
import com.pdd.pop.sdk.http.api.response.PddLogisticsCompaniesGetResponse.LogisticsCompaniesGetResponseLogisticsCompaniesItem;
import com.pdd.pop.sdk.http.api.response.PddWaybillGetResponse.InnerPddWaybillGetResponseModulesItem;
import com.pdd.pop.sdk.http.api.response.PddWaybillSearchResponse.InnerPddWaybillSearchResponseWaybillApplySubscriptionColsItem;
import com.pdd.pop.sdk.http.api.response.PddWaybillSearchResponse.InnerPddWaybillSearchResponseWaybillApplySubscriptionColsItemBranchAccountColsItem;
import com.pdd.pop.sdk.http.api.response.PddWaybillSearchResponse.InnerPddWaybillSearchResponseWaybillApplySubscriptionColsItemBranchAccountColsItemShippAddressColsItem;
import com.pdd.pop.sdk.http.token.AccessTokenResponse;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@Getter
@Setter
public class PDDService implements ILogisticServiceTypeA {

    Logger logger = LoggerFactory.getLogger(PDDService.class);


    private static String ACCESS_TOKEN = "ac7f9f34a49c4a77864c3dcd4d6f11ec698e9679";

    private static final String _PDD_LOGISTIC_SERVICE_STRING = "{ \"SVC-COD\": { \"value\": \"200\" } }";

    private static final String _PDD_ORDER_CHANNEL_TYPE = "PDD";

    final ILogisticBranchInfoService logisticBranchInfoService;

    final ISenderAddressService senderAddressService;

    final
    PinduoduoProperties pddProperties;

    final
    PopClient pddClient;

    final
    PopAccessTokenClient tokenClient;

    @Autowired
    public PDDService(ILogisticBranchInfoService logisticBranchInfoService, ISenderAddressService senderAddressService, PinduoduoProperties pddProperties, PopClient pddClient, PopAccessTokenClient tokenClient) {
        this.logisticBranchInfoService = logisticBranchInfoService;
        this.senderAddressService = senderAddressService;
        this.pddProperties = pddProperties;
        this.pddClient = pddClient;
        this.tokenClient = tokenClient;
    }


    /**
     * 获取access_token
     */
    public void generateToken(String code){
        AccessTokenResponse response = null;
        try{
            response = tokenClient.generate(code);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("error occurred when generate PDD token,detail:"+e.getMessage());
        }
        System.out.println(response.getAccessToken());
        System.out.println(response.getExpiresIn());
        System.out.println(response.getOwnerName());
        System.out.println(response.getRefreshToken());
        System.out.println(response.getScope());
        ACCESS_TOKEN = response.getAccessToken();
    }

    /**
     * 刷新access_token
     */
    public void refresToken(String freshToken){

        try{
//            ACCESS_TOKEN = tokenClient.refresh(pddProperties.getCode()).getAccessToken();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("error occurred when generate PDD token,detail:"+e.getMessage());
        }

    }

    @Override
    public Response<List<WaybillInfo>> getWaybillInfo(List<ExpressInfoHead> expressInfoHeads) {
        return null;
    }

    @Override
    public Response<List<WaybillInfo>> getWaybillInfo(List<ExpressInfoHead> expressInfoHeads, boolean isEncrypt) {
        return null;
    }

    /**
     * 获取拼多多电子面单数据
     * @param expressInfoHeads  批量订单信息
     * @param needEncrypt   是否需要加密
     * @param chineseLogisticName 物流商名称中文模糊查询
     * @return Response<List<WaybillInfo> 返回请求到的运单信息
     */
    public Response<List<WaybillInfo>> getWaybillInfo(List<ExpressInfoHead> expressInfoHeads, boolean needEncrypt, String chineseLogisticName)  {
        String logisticCode;
        String templateUrl;

        //根据中文获取拼多多快递公司代码
        Response<String> companyRes = this.getPDDLogisticCompanyInfo(chineseLogisticName);
        if (!companyRes.isSuccess()){
            return new Response<>(WaybillResultEnum.PDD_ERROR_GET_LOGISTIC_FAIL,new Object[]{companyRes});
        }else {
            logisticCode = companyRes.getResponseData();
        }
        //根据快递公司代码获取拼多多标准模板
        Response<String> templateRes = this.getPDDLogisticTemplate(logisticCode);
        if (!templateRes.isSuccess()){
            return new Response<>(WaybillResultEnum.PDD_ERROR_GET_TEMPLATE_FAIL,new Object[]{templateRes});
        }else {
            templateUrl = templateRes.getResponseData();
        }
        ExpressInfoHead first = expressInfoHeads.get(0);
        //从数据库加载网点地址信息，若没有，则请求远端
        SenderAddress branchAddress = senderAddressService.getOneByLogisticCode(logisticCode,first.getEnterpriseNo(),first.getWarehouseNo());
        if (branchAddress==null){
            Response<SenderAddress> branchRec = this.getPDDSenderBranchInfo(logisticCode,first.getEnterpriseNo(),first.getWarehouseNo());
            if (!branchRec.isSuccess()){
                return new Response<>(WaybillResultEnum.PDD_ERROR_GET_BRANCH_FAIL,new Object[]{branchRec});
            }
            branchAddress = branchRec.getResponseData();
        }


        List<WaybillInfo> waybillInfos = new ArrayList<>();
        List<List<ExpressInfoHead>> taskList= new ArrayList<>();
        //由于拼多多接口最大一次请求10个订单，所以拆分为多次请求
        if (expressInfoHeads.size()>pddProperties.getBatchSize()){
            taskList = CollectionsUtils.listSpilt(expressInfoHeads,pddProperties.getBatchSize());
        }else
            taskList.add(expressInfoHeads);

        //分批请求接口，并返回结果
        for (List<ExpressInfoHead> infoHeads : taskList) {
            PddWaybillGetResponse waybillGetResponse;
            try {
                waybillGetResponse = pddClient.syncInvoke(this.buildPDDRequeset(branchAddress,infoHeads, needEncrypt, templateUrl, logisticCode), ACCESS_TOKEN);
            }catch (Exception e){
                e.printStackTrace();
                logger.error("error occurred when get PDD logistic["+logisticCode+"]["+templateUrl+"]company,detail:"+e.getMessage());
                return new Response<>(WaybillResultEnum.PDD_ERROR_GET_WAYBILL_FAIL,new Object[]{logisticCode,templateUrl,e.getMessage()});
            }

            try{
                List<InnerPddWaybillGetResponseModulesItem> waybillResponses =  waybillGetResponse.getPddWaybillGetResponse().getModules();
                for (InnerPddWaybillGetResponseModulesItem waybillResponse : waybillResponses) {
                    WaybillInfo waybillInfo = new WaybillInfo();
                    waybillInfo.setObjectId(waybillResponse.getObjectId());
                    waybillInfo.setWaybillNo(waybillResponse.getWaybillCode());
                    waybillInfo.setParentWaybillNo(waybillResponse.getParentWaybillCode());
                    waybillInfo.setPrintData(waybillResponse.getPrintData());
                    waybillInfos.add(waybillInfo);
                }
            }catch (Exception e){
                if (waybillGetResponse.getErrorResponse()!=null){
                    return new Response<>(WaybillResultEnum.PDD_ERROR_GET_WAYBILL_FAIL,
                            new Object[]{logisticCode,templateUrl,waybillGetResponse.getErrorResponse().getErrorMsg()+ StringPool.COMMON_SEPARATOR_SPLIT_COLON+waybillGetResponse.getErrorResponse().getSubMsg()});
                }else {
                    logger.error("error occurred when get PDD logistic["+logisticCode+"]["+templateUrl+"]company,detail:"+e.getMessage());
                    return new Response<>(WaybillResultEnum.PDD_ERROR_GET_WAYBILL_FAIL,new Object[]{logisticCode,templateUrl,e.getMessage()});
                }
            }
        }
        return new Response<>(WaybillResultEnum.SUCCESS,waybillInfos);
    }

    /**
     * 私有方法，构建拼多多消息请求体
     * @param branchAddress 网点发货地址
     * @param expressInfoHeads 批量包裹信息
     * @param needEncrypt 是否加密
     * @param templateUrl 打印膜版（仅用于请求运单号）
     * @param logisticCode 合作物流商代码
     * @return PddWaybillGetRequest 拼多多请求对象
     */
    private PddWaybillGetRequest buildPDDRequeset(SenderAddress branchAddress,List<ExpressInfoHead> expressInfoHeads, boolean needEncrypt,String templateUrl,String logisticCode){


        PddWaybillGetRequest request = new PddWaybillGetRequest();
        ParamWaybillCloudPrintApplyNewRequest paramWaybillCloudPrintApplyNewRequest = new ParamWaybillCloudPrintApplyNewRequest();
        paramWaybillCloudPrintApplyNewRequest.setNeedEncrypt(needEncrypt);

        //发货人信息
        ParamWaybillCloudPrintApplyNewRequestSender sender = new ParamWaybillCloudPrintApplyNewRequestSender();
        sender.setName(expressInfoHeads.get(0).getSenderName());
        sender.setMobile(expressInfoHeads.get(0).getSenderMobile());
        sender.setPhone(expressInfoHeads.get(0).getSenderPhone());
        ParamWaybillCloudPrintApplyNewRequestSenderAddress senderAddress = new ParamWaybillCloudPrintApplyNewRequestSenderAddress();
        senderAddress.setProvince(branchAddress.getProvince());
        senderAddress.setCity(branchAddress.getCity());
        senderAddress.setDistrict(branchAddress.getDistrict());
        senderAddress.setTown(branchAddress.getDistrict());
        senderAddress.setDetail(branchAddress.getDetail());
        sender.setAddress(senderAddress);
        paramWaybillCloudPrintApplyNewRequest.setSender(sender);



        List<ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItem> tradeOrderInfoDtos = new ArrayList<>();



        for (ExpressInfoHead expressInfo : expressInfoHeads) {
        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItem tradeOrderInfo = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItem();
        tradeOrderInfo.setLogisticsServices(_PDD_LOGISTIC_SERVICE_STRING);

        //此处用于区分返回的唯一ID，方便处理
        tradeOrderInfo.setObjectId(expressInfo.getEnterpriseNo()
                .concat(StringPool.COMMON_SEPARATOR_SPLIT_COLON)
                .concat(expressInfo.getWarehouseNo())
                .concat(StringPool.COMMON_SEPARATOR_SPLIT_COLON)
                .concat(expressInfo.getExpNo()));


        //订单信息
        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemOrderInfo orderInfo = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemOrderInfo();

        orderInfo.setOrderChannelsType(_PDD_ORDER_CHANNEL_TYPE);

        List<String> orderNoList = new ArrayList<>();
        orderNoList.add(expressInfo.getOrderNo());

        orderInfo.setTradeOrderList(orderNoList);
        //包裹信息
        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfo packageInfo = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfo();
        List<ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfoItemsItem> packageitems = new ArrayList<ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfoItemsItem>();
        expressInfo.getGoodsList().forEach( expressInfoBody ->{
            ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfoItemsItem item =
                    new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfoItemsItem();
            item.setName(expressInfoBody.getGoodName());
            item.setCount(expressInfoBody.getPlanQty().intValue());
            packageitems.add(item);
        });
        packageInfo.setItems(packageitems);

        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipient recipient = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipient();
        recipient.setPhone(expressInfo.getReceivePhone());
        recipient.setMobile(expressInfo.getReceiveMobile());
        recipient.setName(expressInfo.getReceiveName());
        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipientAddress recAddress =
                new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipientAddress();

        recAddress.setProvince(expressInfo.getReceiveProvince());
        recAddress.setCity(expressInfo.getReceiveCity());
        recAddress.setDistrict(expressInfo.getReceiveZone());
        recAddress.setTown(expressInfo.getReceiveZone());
        recAddress.setDetail(expressInfo.getReceiveAddress());
        recipient.setAddress(recAddress);


        tradeOrderInfo.setRecipient(recipient);


        tradeOrderInfo.setTemplateUrl(templateUrl);
        tradeOrderInfo.setUserId(0L);


        tradeOrderInfo.setOrderInfo(orderInfo);
        tradeOrderInfo.setPackageInfo(packageInfo);

        tradeOrderInfoDtos.add(tradeOrderInfo);
        }


        paramWaybillCloudPrintApplyNewRequest.setTradeOrderInfoDtos(tradeOrderInfoDtos);
        paramWaybillCloudPrintApplyNewRequest.setWpCode(logisticCode);
        request.setParamWaybillCloudPrintApplyNewRequest(paramWaybillCloudPrintApplyNewRequest);
        return request;
    }

    /**
     * 取消使用运单号
     * @param wayBillNo 运单号
     * @return
     */
    public Response<Boolean> cancelWaybillNo(String logisticCode,String wayBillNo){

        PddWaybillCancelResponse waybillCancelResponse;
        PddWaybillCancelRequest request = new PddWaybillCancelRequest ();
        request.setWaybillCode(wayBillNo);
        request.setWpCode(logisticCode);

        try {
            waybillCancelResponse = pddClient.syncInvoke(request,ACCESS_TOKEN);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("error occurred when cancel waybill ["+wayBillNo+"],detail:"+e.getMessage());
            return new Response<>(WaybillResultEnum.PDD_ERROR_CANCEL_WAYBILL_FAIL,new Object[]{logisticCode,wayBillNo,e.getMessage()});
        }


        try{
            if (waybillCancelResponse.getPddWaybillCancelResponse().getCancelResult()){
                return new Response<>(WaybillResultEnum.SUCCESS);
            }else {
                logger.error("error occurred whencancel waybill ["+wayBillNo+"],detail:null response but no errorMsg");
                return new Response<>(WaybillResultEnum.PDD_ERROR_CANCEL_WAYBILL_FAIL,new Object[]{logisticCode,wayBillNo,"null response but no errorMsg"});
            }
        }catch(Exception e){
            ErrorResponse error = waybillCancelResponse.getErrorResponse();
            if (error!=null){
                return new Response<>(WaybillResultEnum.PDD_ERROR_CANCEL_WAYBILL_FAIL,
                        new Object[]{logisticCode,wayBillNo,
                                this.convertPDDErrorMsg(error)});
            }else {
                logger.error("error occurred when get PDD logistic["+logisticCode+":"+wayBillNo+"]company,detail:"+e.getMessage());
                return new Response<>(WaybillResultEnum.PDD_ERROR_CANCEL_WAYBILL_FAIL,new Object[]{logisticCode,wayBillNo,e.getMessage()});
            }
        }

    }


    /**
     * 获取拼多多物流商列表
     * @param chineseLogisticName 物流商中文名称
     * @return Response<String> 返回物流公司代码消息结果
     */
    public Response<String>  getPDDLogisticCompanyInfo(String chineseLogisticName) {

        PddLogisticsCompaniesGetResponse companiesGetResponse;
        PddLogisticsCompaniesGetRequest request = new PddLogisticsCompaniesGetRequest();

        String logisticCode = null;

        try {
            companiesGetResponse = pddClient.syncInvoke(request);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("error occurred when get PDD logistic["+chineseLogisticName+"]company,detail:"+e.getMessage());
            return new Response<>(WaybillResultEnum.PDD_ERROR_GET_LOGISTIC_FAIL,new Object[]{chineseLogisticName,e.getMessage()});
        }
        try{
            for (LogisticsCompaniesGetResponseLogisticsCompaniesItem company : companiesGetResponse.getLogisticsCompaniesGetResponse().getLogisticsCompanies()) {
                if (company.getLogisticsCompany().contains(chineseLogisticName) && company.getAvailable()==1){
                    logisticCode = company.getCode();
                }
            }
        }catch(Exception e){
            ErrorResponse error = companiesGetResponse.getErrorResponse();
            if (error!=null){
                return new Response<>(WaybillResultEnum.PDD_ERROR_GET_LOGISTIC_FAIL,
                        new Object[]{chineseLogisticName,
                        this.convertPDDErrorMsg(error)});
            }else {
                logger.error("error occurred when get PDD logistic["+chineseLogisticName+"]company,detail:"+e.getMessage());
                return new Response<>(WaybillResultEnum.PDD_ERROR_GET_LOGISTIC_FAIL,new Object[]{chineseLogisticName,e.getMessage()});
            }
        }

        if (logisticCode==null){
            return new Response<>(WaybillResultEnum.PDD_ERROR_GET_LOGISTIC_FAIL,new Object[]{chineseLogisticName,"response logisticCode is null"});
        }
        return new Response<>(WaybillResultEnum.SUCCESS,logisticCode);
    }

    /**
     * 获取特定物流商的标准模板
     * @param logisticCode 物流商代码
     * @return Response<String>
     */
    public Response<String> getPDDLogisticTemplate(String logisticCode) {

        PddCloudprintStdtemplatesGetRequest request = new PddCloudprintStdtemplatesGetRequest();
        request.setWpCode(logisticCode);

        String templateUrl;
        PddCloudprintStdtemplatesGetResponse response;

        try {
            response = pddClient.syncInvoke(request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("error occurred when get PDD " + logisticCode + "template" + e.getMessage());
            return new Response<>(WaybillResultEnum.ERROR_UNKNOWN, new Object[]{logisticCode,e.getMessage()});
        }

        try {
            templateUrl = response.getPddCloudprintStdtemplatesGetResponse().getResult().getDatas().get(0).getStandardTemplates().get(0).getStandardTemplateUrl();
        } catch (Exception e) {
            ErrorResponse error = response.getErrorResponse();
            if (error!= null) {
                return new Response<>(WaybillResultEnum.PDD_ERROR_GET_TEMPLATE_FAIL,
                        new Object[]{logisticCode,this.convertPDDErrorMsg(error)});
            } else {
                logger.error("error occurred when get PDD " + logisticCode + "template" + e.getMessage());
                return new Response<>(WaybillResultEnum.PDD_ERROR_GET_TEMPLATE_FAIL, new Object[]{logisticCode,e.getMessage()});
            }
        }
        if (templateUrl==null){
            return new Response<>(WaybillResultEnum.PDD_ERROR_GET_TEMPLATE_FAIL,new Object[]{logisticCode,"response templateUrl is null"});
        }
        return new Response<>(WaybillResultEnum.SUCCESS, templateUrl);
    }


    /**
     * 获取拼多多网点合作仓的发货地址信息
     * @param logisticCode 合作物流商代码
     * @return Response<SenderAddress> 保存数据库的同时返回信息
     */
    @Transactional
    public Response<SenderAddress> getPDDSenderBranchInfo(String logisticCode,String enterpriseNo,String warehouseNo){

        PddWaybillSearchRequest request = new PddWaybillSearchRequest();
        PddWaybillSearchResponse response;
        request.setWpCode(logisticCode);
        try {
            response = this.pddClient.syncInvoke(request, ACCESS_TOKEN);
        }catch (Exception e){
            logger.error("error occurred when get PDD logistic "+logisticCode+"branch,detail:" + e.getMessage());
            return new Response<>(WaybillResultEnum.PDD_ERROR_GET_BRANCH_FAIL,new Object[]{logisticCode,e.getMessage()});
        }
         List<InnerPddWaybillSearchResponseWaybillApplySubscriptionColsItem> branchList = null;
        try{
            branchList = response.getPddWaybillSearchResponse().getWaybillApplySubscriptionCols();
        }catch (Exception e) {
            ErrorResponse error = response.getErrorResponse();
            if (error != null) {
                return new Response<>(WaybillResultEnum.PDD_ERROR_GET_BRANCH_FAIL, new Object[]{logisticCode,
                        this.convertPDDErrorMsg(error)});
            } else {
                logger.error("error occurred when get PDD logistic ["+logisticCode+"] branch,detail:" + e.getMessage());
                return new Response<>(WaybillResultEnum.PDD_ERROR_GET_BRANCH_FAIL, new Object[]{logisticCode, e.getMessage()});
            }
        }

        //保存网点以及发货人信息
        List<LogisticBranchInfo> branchInfos= new ArrayList<>();
        List<SenderAddress> senderAddresses= new ArrayList<>();

        for (InnerPddWaybillSearchResponseWaybillApplySubscriptionColsItem branches : branchList) {
            for (InnerPddWaybillSearchResponseWaybillApplySubscriptionColsItemBranchAccountColsItem branch : branches.getBranchAccountCols()) {
                LogisticBranchInfo branchInfo = new LogisticBranchInfo();
                branchInfo.setBranchCode(branch.getBranchCode());
                branchInfo.setBranchName(branch.getBranchName());
                branchInfo.setLogisticCode(branches.getWpCode());
                branchInfo.setQuantity(branch.getQuantity());
                branchInfo.setCancelQuantity(branch.getCancelQuantity());
                branchInfo.setRecycledQuantity(branch.getRecycledQuantity());
                for (InnerPddWaybillSearchResponseWaybillApplySubscriptionColsItemBranchAccountColsItemShippAddressColsItem col : branch.getShippAddressCols()) {
                    SenderAddress address = new SenderAddress();
                    address.setProvince(col.getProvince());
                    address.setCity(col.getCity());
                    address.setDistrict(col.getDistrict());
                    address.setDetail(col.getDetail());
                    address.setEnterpriseNo(enterpriseNo);
                    address.setWarehouseNo(warehouseNo);
                    address.setBranchCode(branch.getBranchCode());
                    senderAddresses.add(address);
                }
                branchInfos.add(branchInfo);
            }
        }

        if (senderAddresses.size()<1){
            return new Response<>(WaybillResultEnum.PDD_ERROR_GET_BRANCH_FAIL,new Object[]{logisticCode,"empty sender address，please check pinduoduo background"});
        }
        if (!logisticBranchInfoService.saveBatch(branchInfos)
        || !senderAddressService.saveBatch(senderAddresses)){
            return new Response<>(WaybillResultEnum.PDD_ERROR_GET_BRANCH_FAIL,new Object[]{logisticCode,"branch or address save fail."});
        }
        return new Response<>(WaybillResultEnum.SUCCESS,senderAddresses.get(0));
    }

    /**
     *  获取指定电子运单的详细信息，包含三段码，配送站点等
     * @param logisticCode 物流商代码
     * @param waybillCode 运单号
     * @return Response<String>
     */
   /* public Response<String> getPDDDeliverAddress(String logisticCode,String waybillCode){


        PddWaybillQueryByWaybillcodeRequest request = new PddWaybillQueryByWaybillcodeRequest();
        List<ParamListItem> paramList = new ArrayList<ParamListItem>();

        ParamListItem item = new ParamListItem();

        item.setObjectId(this.generateObjectId());
        item.setWaybillCode(waybillCode);
        item.setWpCode(logisticCode);
        paramList.add(item);
        request.setParamList(paramList);
        PddWaybillQueryByWaybillcodeResponse response;
        try {
            response = pddClient.syncInvoke(request, ACCESS_TOKEN);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try{
            response.getPddWaybillQueryByWaybillcodeResponse().getModules().get(0).getWaybillCloudPrintResponse().getPrintData()
        }catch (Exception e){

        }
    }*/


    /**
     * 格式化转换拼多多错误信息为字符串
     * @return 拼接后的错误信息
     */
    private String convertPDDErrorMsg(ErrorResponse errorResponse){
        return new StringBuilder().append("[")
                .append(errorResponse.getErrorCode())
                .append("]")
                .append(errorResponse.getErrorMsg())
                .append("[[")
                .append(errorResponse.getSubCode())
                .append("]")
                .append(errorResponse.getSubMsg())
                .append("]")
                .toString();
    }

    /**
     * 获取请求ID字符串
     * @return
     */
    private String generateObjectId(){
        return WmsTimeUtils.getCurrentDatetime();
    }
}
